const express = require('express');
const dotenv = require('dotenv');
const path = require('path');
const fs = require('fs');
const cors = require('cors');
const { engine } = require('express-handlebars');
const { networkInterfaces } = require('os');

// 加载.env文件
dotenv.config({ path: path.resolve(__dirname, '.env') });

// 从环境变量读取配置
console.log('读取.env文件配置...');
console.log(`WS_URL环境变量值: ${process.env.WS_URL}`);
console.log(`DEVICE_TOKEN环境变量值: ${process.env.DEVICE_TOKEN}`);
console.log(`WEB_PORT环境变量值: ${process.env.WEB_PORT}`);
console.log(`PROXY_PORT环境变量值: ${process.env.PROXY_PORT}`);
console.log(`ENABLE_TOKEN环境变量值: ${process.env.ENABLE_TOKEN}`);
console.log(`LOCAL_PROXY_URL环境变量值: ${process.env.LOCAL_PROXY_URL}`);
console.log(`CLIENT_ID环境变量值: ${process.env.CLIENT_ID}`);

const WS_URL = process.env.WS_URL || 'wss://api.tenclass.net/xiaozhi/v1/';
const PROXY_PORT = parseInt(process.env.PROXY_PORT) || 8893;
const WEB_PORT = parseInt(process.env.WEB_PORT) || 8889;
const TOKEN = process.env.DEVICE_TOKEN || 'test-token';
const ENABLE_TOKEN = process.env.ENABLE_TOKEN === 'true';
const LOCAL_PROXY_URL = process.env.LOCAL_PROXY_URL || 'ws://localhost:8893';
const CLIENT_ID = process.env.CLIENT_ID || 'a043b25c-3088-4484-aa4b-2b90caed5193';

let proxyServer = null;

// 获取MAC地址
function getMacAddress() {
    // const interfaces = networkInterfaces();
    // for (const interfaceName in interfaces) {
    //     const iface = interfaces[interfaceName];
    //     for (const alias of iface) {
    //         if (alias.family === 'IPv4' && !alias.internal && alias.mac && alias.mac !== '00:00:00:00:00:00') {
    //             return alias.mac;
    //         }
    //     }
    // }
    // // 如果找不到MAC地址，返回默认值
    // return '00:00:00:00:00:00';
    return "94:a9:90:1a:e2:08";
}

// 导出配置供其他模块使用
module.exports = {
    WS_URL,
    PROXY_PORT,
    WEB_PORT,
    TOKEN,
    ENABLE_TOKEN,
    LOCAL_PROXY_URL,
    getMacAddress,
    CLIENT_ID
};

// 导入WebSocket代理模块
const WebSocketProxy = require('./proxy');

// 启动WebSocket代理服务器
function startProxyServer() {
    try {
        console.log(`准备启动WebSocket代理服务器:`);
        console.log(`  - 本地代理端口: ${PROXY_PORT}`);
        console.log(`  - 远程服务器URL: ${WS_URL}`);
        console.log(`  - 启用Token: ${ENABLE_TOKEN}`);
        console.log(`  - Token值: ${ENABLE_TOKEN ? TOKEN : '未启用'}`);
        
        proxyServer = new WebSocketProxy(PROXY_PORT, WS_URL);
        proxyServer.start();
        console.log(`WebSocket代理服务器启动成功，监听端口: ${PROXY_PORT}`);
        console.log(`前端WebSocket连接URL: ${LOCAL_PROXY_URL}`);
    } catch (error) {
        console.error(`WebSocket代理服务器启动失败: ${error}`);
        console.error(`错误详情:`, error);
    }
}

// 创建Express应用
const app = express();

// 配置中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 配置静态文件目录
const staticPath = path.join(__dirname, 'static');
console.log(`静态文件目录: ${staticPath}`);
console.log(`静态文件目录是否存在: ${fs.existsSync(staticPath)}`);
// 添加/static路径前缀
app.use('/static', express.static(staticPath));

// 配置Handlebars模板引擎
app.engine('.html', engine({
    extname: '.html',
    layoutsDir: path.join(__dirname, '.', 'templates'),
    partialsDir: path.join(__dirname, '.', 'templates/partials'),
    defaultLayout: false
}));
app.set('view engine', '.html');
app.set('views', path.join(__dirname, '.', 'templates'));

// 路由配置
app.get('/', (req, res) => {
    res.render('index', {
        local_proxy_url: LOCAL_PROXY_URL,
        ws_url: WS_URL,
        enable_token: ENABLE_TOKEN,
        token: TOKEN,
        clientId: CLIENT_ID,
        device_id: getMacAddress()
    });
});

// 测试静态文件路由
app.get('/test-static', (req, res) => {
    const cssFilePath = path.join(staticPath, 'styles.css');
    console.log(`尝试读取CSS文件: ${cssFilePath}`);
    console.log(`文件是否存在: ${fs.existsSync(cssFilePath)}`);
    if (fs.existsSync(cssFilePath)) {
        res.sendFile(cssFilePath);
    } else {
        res.status(404).send('File not found');
    }
});

app.get('/test_connection', async (req, res) => {
    try {
        const result = {
            status: 'success',
            message: '连接测试成功',
            config: {
                wsUrl: WS_URL,
                proxyPort: PROXY_PORT,
                webPort: WEB_PORT,
                enableToken: ENABLE_TOKEN,
                deviceId: getMacAddress(),
                clientId: CLIENT_ID
            }
        };
        res.json(result);
    } catch (error) {
        res.status(500).json({
            status: 'error',
            message: error.message
        });
    }
});

app.post('/save_config', express.json(), (req, res) => {
    try {
        const { ws_url, local_proxy_url, token, enable_token } = req.body;
        
        // 读取当前.env文件内容
        let envContent = fs.readFileSync(path.join(__dirname, '..', '.env'), 'utf8');
        
        // 更新配置项
        envContent = envContent.replace(/WS_URL=.*/, `WS_URL=${ws_url}`);
        envContent = envContent.replace(/LOCAL_PROXY_URL=.*/, `LOCAL_PROXY_URL=${local_proxy_url}`);
        envContent = envContent.replace(/DEVICE_TOKEN=.*/, `DEVICE_TOKEN=${token}`);
        envContent = envContent.replace(/ENABLE_TOKEN=.*/, `ENABLE_TOKEN=${enable_token}`);
        
        fs.writeFileSync(path.join(__dirname, '..', '.env'), envContent);
        
        res.json({
            status: 'success',
            message: '配置保存成功，请重启应用以应用新配置'
        });
    } catch (error) {
        res.status(500).json({
            status: 'error',
            message: error.message
        });
    }
});

// 启动服务器
function startServer() {
    try {
        // 启动Express服务器
        app.listen(WEB_PORT, () => {
            console.log(`Web服务器启动成功，访问地址: http://localhost:${WEB_PORT}`);
        });
        
        // 启动WebSocket代理服务器
        startProxyServer();
        
    } catch (error) {
        console.error(`服务器启动失败: ${error}`);
    }
}

// 优雅退出处理
process.on('SIGINT', () => {
    console.log('正在关闭服务器...');
    if (proxyServer) {
        proxyServer.close();
    }
    console.log('服务器已关闭');
    process.exit(0);
});

// 启动服务器
startServer();